using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Reflection;
using T2V.SharePoint.Common.Helpers;
using T2V.SharePoint.Common.Models;
using T2V.SharePoint.Common.Extensions;
using PepsiCo.Common;

namespace PepsiCo.Intranet.Features.PepsiCo.Site
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("64831c27-982f-4cd0-b341-811281e9818c")]
    public class PepsiCoSiteEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;
            SPWeb web = site.RootWeb;
            bool isAllowUnsafeUpdates = web.AllowUnsafeUpdates;

            try
            {
                web.AllowUnsafeUpdates = true;

                Uri siteMaster = new Uri(string.Format("{0}/_catalogs/masterpage/PepsiCo.master", web.Url));
                web.MasterUrl = siteMaster.AbsolutePath;
                web.CustomMasterUrl = siteMaster.AbsolutePath;
                web.Update();

                EnsureWebFeatureActivatedWithReActivated(new Guid(PepsiCoConstants.PEPSICO_ROOTWEB_FEATURE_ID), site, web);
                EnsureWebFeatureActivated(new Guid(PepsiCoConstants.PEPSICO_ROOTWEB_DATA_FEATURE_ID), site, web);
               
                ProvisionSubSitesStructure(web);
            }
            catch
            {
            }
            finally
            {
                web.AllowUnsafeUpdates = isAllowUnsafeUpdates;
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = (SPSite)properties.Feature.Parent;
            SPWeb web = site.RootWeb;
            bool isAllowUnsafeUpdates = web.AllowUnsafeUpdates;

            try
            {
                web.AllowUnsafeUpdates = true;

                Uri siteMaster = new Uri(string.Format("{0}/_catalogs/masterpage/v4.master", web.Url));
                web.MasterUrl = siteMaster.AbsolutePath;
                web.CustomMasterUrl = siteMaster.AbsolutePath;
                web.Update();
            }
            catch
            {
            }
            finally
            {
                web.AllowUnsafeUpdates = isAllowUnsafeUpdates;
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private void ProvisionSubSitesStructure(SPWeb web)
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                string xml = assembly.GetResourceTextFile("PepsiCo.Intranet.XMLCustomSettings.SiteStructures.xml");

                var subsites = SerializationHelper.DeserializeFromXml<WebDefinitionCollection>(xml);
                web.ProvisionWebStructure(subsites);

            }
            catch (Exception ex)
            {
                
            }
        }

        private void EnsureWebFeatureActivated(Guid featureGuid, SPSite lSite, SPWeb lWeb)
        {
            using (SPSite site = new SPSite(lSite.ID))
            {
                using (SPWeb web = site.OpenWeb(lWeb.ID))
                {
                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true;
                    SPFeature feature = null;
                    try
                    {
                        feature = web.Features[featureGuid];
                        if (feature == null)
                        {
                            web.Features.Add(featureGuid, false);
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                    site.AllowUnsafeUpdates = false;
                    web.AllowUnsafeUpdates = false;
                }
            }
        }

        private void EnsureWebFeatureActivatedWithReActivated(Guid featureGuid, SPSite lSite, SPWeb lWeb)
        {
            bool isDeactivated = false;

            using (SPSite site = new SPSite(lSite.ID))
            {
                using (SPWeb web = site.OpenWeb(lWeb.ID))
                {
                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true;
                    SPFeature feature = null;
                    try
                    {
                        feature = web.Features[featureGuid];
                        if (feature == null)
                        {
                            web.Features.Add(featureGuid, false);
                        }
                        else
                        {
                            web.Features.Remove(feature.DefinitionId);
                            isDeactivated = true;
                        }
                    }
                    catch (Exception ex)
                    {

                    }
                    site.AllowUnsafeUpdates = false;
                    web.AllowUnsafeUpdates = false;
                }
            }

            //re-activate, must re-new SPSite and SPWeb
            if (isDeactivated == true)
            {
                using (SPSite site = new SPSite(lSite.ID))
                {
                    using (SPWeb web = site.OpenWeb(lWeb.ID))
                    {
                        site.AllowUnsafeUpdates = true;
                        web.AllowUnsafeUpdates = true;
                        SPFeature feature = null;
                        try
                        {
                            feature = web.Features[featureGuid];
                            if (feature == null)
                            {
                                web.Features.Add(featureGuid, false);
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                        site.AllowUnsafeUpdates = false;
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }

        }
    }
}
